const api = require('../../utils/api');
const reminderApi = api.reminder;
const app = getApp();

Page({
  data: {
    id: null,
    reminder: null,
    loading: true,
    error: null,
    completionHistory: []
  },

  onLoad(options) {
    if (options && options.id) {
      this.setData({ id: options.id });
      this.fetchReminderDetail();
    } else {
      this.setData({
        loading: false,
        error: '未找到提醒ID'
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.showToast({
          title: '参数无效，即将返回',
          icon: 'none'
        });
        setTimeout(() => {
          // 检查页面栈深度
          const pages = getCurrentPages();
          if (pages.length > 1) {
            wx.navigateBack();
          } else {
            wx.redirectTo({
              url: '/pages/healthReminder/healthReminder'
            });
          }
        }, 1500);
      }, 500);
    }
  },

  onPullDownRefresh() {
    this.fetchReminderDetail(true);
  },

  async fetchReminderDetail(showRefreshLoading = false) {
    if (showRefreshLoading) {
      wx.showNavigationBarLoading();
    } else {
      this.setData({ loading: true });
    }
    
    try {
      // 检查API和ID是否有效
      if (!reminderApi) {
        throw new Error('提醒API未初始化');
      }
      
      if (!this.data.id) {
        throw new Error('提醒ID无效');
      }
      
      const reminder = await reminderApi.getReminderById(this.data.id);
      
      if (!reminder) {
        throw new Error('未找到提醒信息');
      }
      
      // 格式化重复日期
      const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
      let repeatText = '';
      
      if (reminder.repeatDays && reminder.repeatDays.length > 0) {
        if (reminder.repeatDays.length === 7) {
          repeatText = '每天';
        } else {
          repeatText = '每周 ' + reminder.repeatDays.map(day => weekDays[day]).join(', ');
        }
      } else {
        repeatText = '不重复';
      }
      
      // 格式化时间
      const timeText = `${reminder.hour < 10 ? '0' + reminder.hour : reminder.hour}:${reminder.minute < 10 ? '0' + reminder.minute : reminder.minute}`;
      
      // 格式化下次提醒时间
      let nextOccurrenceText = '无';
      if (reminder.nextOccurrence) {
        const nextDate = new Date(reminder.nextOccurrence);
        nextOccurrenceText = `${nextDate.getFullYear()}-${nextDate.getMonth() + 1}-${nextDate.getDate()} ${timeText}`;
      }
      
      // 处理类型文本
      const typeText = reminder.type === 'medicine' ? '用药提醒' : 
                    reminder.type === 'glucose' ? '血糖测量' : 
                    reminder.type === 'exercise' ? '运动提醒' : 
                    reminder.type === 'diet' ? '饮食提醒' : '一般提醒';
      
      // 处理优先级文本
      const priorityText = reminder.priority === 'high' ? '高' : 
                       reminder.priority === 'medium' ? '中' : '低';
      
      // 处理完成历史
      let completionHistory = [];
      if (reminder.completionHistory && reminder.completionHistory.length > 0) {
        completionHistory = reminder.completionHistory.map(history => {
          const date = new Date(history.date);
          return {
            ...history,
            dateFormatted: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
          };
        });
      }
      
      this.setData({
        reminder: {
          ...reminder,
          repeatText,
          timeText,
          nextOccurrenceText,
          typeText,
          priorityText
        },
        completionHistory,
        loading: false,
        error: null
      });
    } catch (error) {
      console.error('获取提醒详情失败', error);
      this.setData({
        loading: false,
        error: '获取提醒详情失败，请稍后重试'
      });
    } finally {
      if (showRefreshLoading) {
        wx.stopPullDownRefresh();
        wx.hideNavigationBarLoading();
      }
    }
  },

  navigateToEdit() {
    wx.navigateTo({
      url: `/pages/reminderEdit/reminderEdit?id=${this.data.id}`
    });
  },

  async handleToggleEnable() {
    wx.showLoading({ title: '更新中...' });
    
    try {
      const updatedData = {
        enabled: !this.data.reminder.enabled
      };
      
      await reminderApi.updateReminder(this.data.id, updatedData);
      
      // 刷新数据
      this.fetchReminderDetail();
      
      wx.showToast({
        title: updatedData.enabled ? '已启用提醒' : '已禁用提醒',
        icon: 'success'
      });
    } catch (error) {
      console.error('更新提醒状态失败', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  async handleCompleteReminder() {
    wx.showLoading({ title: '更新中...' });
    
    try {
      await reminderApi.completeReminder(this.data.id);
      
      // 刷新数据
      this.fetchReminderDetail();
      
      wx.showToast({
        title: '已完成提醒',
        icon: 'success'
      });
    } catch (error) {
      console.error('完成提醒失败', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  async handleSnoozeReminder() {
    wx.showActionSheet({
      itemList: ['延迟 15 分钟', '延迟 30 分钟', '延迟 1 小时', '延迟到明天'],
      success: async (res) => {
        let minutes = 30;
        
        switch (res.tapIndex) {
          case 0:
            minutes = 15;
            break;
          case 1:
            minutes = 30;
            break;
          case 2:
            minutes = 60;
            break;
          case 3:
            minutes = 24 * 60;
            break;
        }
        
        wx.showLoading({ title: '更新中...' });
        
        try {
          await reminderApi.snoozeReminder(this.data.id, minutes);
          
          // 刷新数据
          this.fetchReminderDetail();
          
          wx.showToast({
            title: `已延迟${minutes}分钟`,
            icon: 'success'
          });
        } catch (error) {
          console.error('延迟提醒失败', error);
          wx.showToast({
            title: '操作失败，请重试',
            icon: 'none'
          });
        } finally {
          wx.hideLoading();
        }
      }
    });
  },

  handleDeleteReminder() {
    wx.showModal({
      title: '确认删除',
      content: '确定删除这个提醒吗？此操作不可撤销。',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          
          try {
            await reminderApi.deleteReminder(this.data.id);
            
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
            
            // 返回上一页
            setTimeout(() => {
              // 检查页面栈深度
              const pages = getCurrentPages();
              if (pages.length > 1) {
                wx.navigateBack();
              } else {
                wx.redirectTo({
                  url: '/pages/healthReminder/healthReminder'
                });
              }
            }, 1500);
          } catch (error) {
            console.error('删除提醒失败', error);
            wx.showToast({
              title: '删除失败，请重试',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  }
}); 